package 设计模式.结构型.代理模式.模板;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Description
 * @Author zhengqiang.tan
 * @Date 2024-10-28
 */
public class Client4 {

    interface Subject {
        void doSomething(String str);
    }

    static class RealSubject implements Subject {
        public void doSomething(String str) {
            System.out.println("I am doing something " + str);
        }

    }

    class MyInvocationHandler implements InvocationHandler {
        private Object obj;

        public MyInvocationHandler(Object obj) {
            this.obj = obj;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return method.invoke(this.obj, args);
        }
    }


    // 通知处理器
    interface IAdvice {
        void exec();
    }

    static class MyAdvice implements IAdvice {
        public void exec() {
            System.out.println("pre handle ...");
        }
    }

    public static void main(String[] args) {
        // 创建被代理对象
        Subject realSubject = new RealSubject();

        // 创建自定义的 InvocationHandler
        InvocationHandler handler = new Client4().new MyInvocationHandler(realSubject);

        // 定义主题的代理
        Subject subject = DynamicProxy.newProxyInstance(realSubject.getClass().getClassLoader(), realSubject.getClass().getInterfaces(), handler);

        // 代理调用
        subject.doSomething("test");
    }
}